import React, { useEffect, useState } from 'react';
import { Card, Form, Alert } from 'react-bootstrap';

const PerformanceAndFileConfig = ({ config, setConfig }) => {
  // 组件内部默认配置 - 与后端保持一致
  const defaultConfig = {
    serverConfig: 'serverDZ.cfg',
    serverProfile: 'profiles',
    logDir: 'logs/',
    rptLog: 'server_console.log',
    instanceId: 1,
    missionTemplate: 'ChernarusPlus',
    backupPath: 'backups',
    backupCount: 5,
    networkPacketSize: 128,
    shardId: 1,
    // 核心性能配置项
    serverFps: 60,
    numberOfCPUThreads: 4,
    disableFpsLimit: 0,
    maxCpuCores: 4,
    memoryOptimization: false,
    maxMemory: 4096,
    networkUpdateRate: 30,
    // 网络与渲染配置
    objectUpdateDistance: 100, // 默认值：100米
    packetCompression: true,
    dynamicLOD: false,
    // 网络范围配置
    networkRangeClose: 20,
    networkRangeNear: 150,
    networkRangeFar: 1000,
    // 其他重要配置
    logAverageFps: 1,
    logMemory: 1,
    cpuCount: -1,
    limitFPS: 100,
    filePatching: true,
    scriptDebug: false,
    scrAllowFileWrite: true,
    freezeCheck: true,
    adminLog: true,
    netLog: true
  };

  // 组件内部状态，用于表单输入临时存储
  const [localConfig, setLocalConfig] = useState(defaultConfig);
  const [missionTemplates, setMissionTemplates] = useState([]);
  const [loadingTemplates, setLoadingTemplates] = useState(false);
  const [templateError, setTemplateError] = useState(null);

  // 当外部config变化时，更新内部localConfig
  useEffect(() => {
    const mergedConfig = {
      ...defaultConfig,
      ...config
    };
    setLocalConfig(mergedConfig);
  }, [config]);

  // 获取任务模板列表
  useEffect(() => {
    const fetchMissionTemplates = async () => {
      setLoadingTemplates(true);
      setTemplateError(null);
      try {
        // 直接指向后端服务器的API地址
        const response = await fetch('http://localhost:5000/api/mission-templates');
        if (!response.ok) throw new Error('获取任务模板失败');
        const data = await response.json();
        
        // 确保data.templates是数组格式
        if (data && Array.isArray(data.templates)) {
          setMissionTemplates(data.templates);
          
          // 如果当前没有选择模板，选择第一个可用的模板
          if (!localConfig.missionTemplate && data.templates.length > 0) {
            handleConfigChange('missionTemplate', data.templates[0].value);
          }
        } else {
          // 如果返回不是数组，使用默认模板
          setMissionTemplates([
            { label: 'Chernarus Plus', value: 'ChernarusPlus' },
            { label: 'Enoch', value: 'enoch' },
            { label: 'Sakhalin', value: 'Sakhalin' }
          ]);
        }
      } catch (error) {
        console.error('获取任务模板时出错:', error);
        setTemplateError('无法获取任务模板，请检查服务器连接');
        
        // 使用默认模板作为备选
        setMissionTemplates([
          { label: 'Chernarus Plus', value: 'ChernarusPlus' },
          { label: 'Enoch', value: 'enoch' },
          { label: 'Sakhalin', value: 'Sakhalin' }
        ]);
      } finally {
        setLoadingTemplates(false);
      }
    };

    fetchMissionTemplates();
  }, []);

  // 处理配置变更，同时更新本地状态和全局配置
  const handleConfigChange = (key, value) => {
    setLocalConfig(prev => ({ ...prev, [key]: value }));
    setConfig(prev => ({ ...prev, [key]: value }));
  };

  return (
    <Card className="h-100 border-3 shadow-medium" style={{backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(15px)', borderColor: '#17a2b8', boxShadow: '0 0 20px rgba(23, 162, 184, 0.5), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 0 10px rgba(23, 162, 184, 0.2)'}}>
      <Card.Header style={{backgroundColor: 'rgba(40, 40, 40, 0.7)', backdropFilter: 'blur(15px)'}}>
        <h3 style={{color: 'var(--primary-color)'}}>性能和文件配置</h3>
      </Card.Header>
      <Card.Body style={{color: '#ffffff', maxHeight: '70vh', overflowY: 'auto'}}>
        {/* 任务模板设置 */}
        <h4 style={{color: '#ff6b6b', marginBottom: '15px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '5px'}}>任务模板设置</h4>
        
        {templateError && (
          <Alert variant="danger" style={{marginBottom: '15px', backgroundColor: 'rgba(220, 53, 69, 0.1)', borderColor: '#dc3545', color: '#ffffff'}}>
            {templateError}
          </Alert>
        )}
        
        <Form.Group className="mb-6">
          <Form.Label>选择任务模板</Form.Label>
          {loadingTemplates ? (
            <div className="text-center py-2">加载中...</div>
          ) : (
            <Form.Select
              value={localConfig.missionTemplate || ''}
              onChange={(e) => handleConfigChange('missionTemplate', e.target.value)}
              className="glass-input"
              style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
            >
              <option value="">请选择任务模板</option>
              {missionTemplates.map((template) => (
                <option key={template.value} value={template.value}>
                  {template.label}
                </option>
              ))}
            </Form.Select>
          )}
          <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
            选择要在服务器上运行的任务模板
          </Form.Text>
        </Form.Group>



        {/* 性能优化设置 */}
        <h4 style={{color: '#ff6b6b', marginBottom: '15px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '5px'}}>性能优化设置</h4>
        <div className="row mb-4">
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>服务器FPS限制</Form.Label>
              <Form.Control
                type="number"
                value={localConfig.serverFps}
                onChange={(e) => handleConfigChange('serverFps', parseInt(e.target.value) || 60)}
                min="15"
                max="120"
                className="glass-input"
                style={{ backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff' }}
              />
              <Form.Text className="text-muted" style={{ color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem' }}>
                服务器最大帧率，较高的值会提高游戏流畅度但增加服务器负载
              </Form.Text>
            </Form.Group>
          </div>
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Check
                type="switch"
                id="disableFpsLimit"
                label="禁用FPS限制"
                checked={localConfig.disableFpsLimit === 1}
                onChange={() => handleConfigChange('disableFpsLimit', localConfig.disableFpsLimit === 1 ? 0 : 1)}
                style={{ color: '#ffffff' }}
                className="form-switch-glow"
              />
              <Form.Text className="text-muted" style={{ color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem' }}>
                禁用服务器帧率限制，可能提高性能但增加硬件消耗
              </Form.Text>
            </Form.Group>
          </div>
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>CPU核心数</Form.Label>
              <Form.Control
                type="number"
                value={localConfig.numberOfCPUThreads}
                onChange={(e) => handleConfigChange('numberOfCPUThreads', parseInt(e.target.value) || 4)}
                min="1"
                max="16"
                className="glass-input"
                style={{ backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff' }}
              />
              <Form.Text className="text-muted" style={{ color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem' }}>
                服务器使用的CPU线程数
              </Form.Text>
            </Form.Group>
          </div>
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>最大CPU核心数</Form.Label>
              <Form.Control
                type="number"
                value={localConfig.maxCpuCores}
                onChange={(e) => handleConfigChange('maxCpuCores', parseInt(e.target.value) || 4)}
                min="1"
                max="16"
                className="glass-input"
                style={{ backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff' }}
              />
              <Form.Text className="text-muted" style={{ color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem' }}>
                服务器可以使用的最大CPU核心数
              </Form.Text>
            </Form.Group>
          </div>
        </div>

        {/* 高级性能配置 */}
        <h4 style={{color: '#ff6b6b', marginBottom: '15px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '5px'}}>高级性能配置</h4>
        <div className="row mb-4">
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>网络包大小</Form.Label>
              <Form.Control 
                type="number" 
                min="64" 
                max={1024} 
                value={localConfig.networkPacketSize} 
                onChange={(e) => handleConfigChange('networkPacketSize', parseInt(e.target.value) || 128)} 
                className="glass-input"
                style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
              />
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                网络数据包大小（字节）
              </Form.Text>
            </Form.Group>
          </div>
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>网络更新频率 (Hz)</Form.Label>
              <Form.Control
                type="number"
                value={localConfig.networkUpdateRate}
                onChange={(e) => handleConfigChange('networkUpdateRate', parseInt(e.target.value) || 30)}
                min="10"
                max="60"
                className="glass-input"
                style={{ backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff' }}
              />
              <Form.Text className="text-muted" style={{ color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem' }}>
                服务器网络更新频率
              </Form.Text>
            </Form.Group>
          </div>
        </div>
        
        <div className="row mb-4">
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Check
                type="switch"
                label="启用内存优化"
                checked={localConfig.memoryOptimization}
                onChange={(e) => handleConfigChange('memoryOptimization', e.target.checked)}
                className="form-switch-glow"
                style={{ color: '#ffffff' }}
              />
              <Form.Text className="text-muted" style={{ color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem' }}>
                启用后会自动清理不必要的内存占用
              </Form.Text>
            </Form.Group>
          </div>
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>最大内存使用量 (MB)</Form.Label>
              <Form.Control
                type="number"
                value={localConfig.maxMemory}
                onChange={(e) => handleConfigChange('maxMemory', parseInt(e.target.value) || 4096)}
                min="2048"
                max="32768"
                className="glass-input"
                style={{ backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff' }}
              />
              <Form.Text className="text-muted" style={{ color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem' }}>
                建议设置为可用内存的70-80%
              </Form.Text>
            </Form.Group>
          </div>
        </div>
        
        <div className="row mb-4">
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Check
                type="switch"
                label="启用数据包压缩"
                checked={localConfig.packetCompression}
                onChange={(e) => handleConfigChange('packetCompression', e.target.checked)}
                className="form-switch-glow"
                style={{ color: '#ffffff' }}
              />
              <Form.Text className="text-muted" style={{ color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem' }}>
                启用网络数据包压缩（默认：开启）。可以显著减少服务器带宽使用，尤其在多人游戏环境中效果明显。
              </Form.Text>
            </Form.Group>
          </div>
        </div>
        
        <div className="row mb-4">
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>对象更新距离 (米)</Form.Label>
              <Form.Control
                type="number"
                value={localConfig.objectUpdateDistance}
                onChange={(e) => handleConfigChange('objectUpdateDistance', parseInt(e.target.value) || 100)}
                min="50"
                max="500"
                className="glass-input"
                style={{ backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff' }}
              />
              <Form.Text className="text-muted" style={{ color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem' }}>
                服务器更新游戏对象的距离范围（默认：100米）。较低值(50-100米)可提高服务器性能和减少带宽使用；较高值(100-500米)可增强游戏世界细节，但会增加服务器负载。
              </Form.Text>
            </Form.Group>
          </div>
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Check
                type="switch"
                label="启用动态LOD"
                checked={localConfig.dynamicLOD}
                onChange={(e) => handleConfigChange('dynamicLOD', e.target.checked)}
                className="form-switch-glow"
                style={{ color: '#ffffff' }}
              />
              <Form.Text className="text-muted" style={{ color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem' }}>
                启用动态LOD系统（默认：关闭）。根据在线玩家数量自动调整服务器性能参数，优化不同负载下的游戏体验。
              </Form.Text>
            </Form.Group>
          </div>
        </div>
        
        <div className="row mb-4">
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Check
                type="switch"
                label="禁用日志记录"
                checked={localConfig.noLogs}
                onChange={(e) => handleConfigChange('noLogs', e.target.checked)}
                className="form-switch-glow"
                style={{ color: '#ffffff' }}
              />
              <Form.Text className="text-muted" style={{ color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem' }}>
                禁用所有日志记录以提高性能
              </Form.Text>
            </Form.Group>
          </div>
        </div>

        {/* 文件和路径配置 */}
        <h4 style={{color: '#ff6b6b', marginBottom: '15px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '5px'}}>文件和路径配置</h4>
        <div className="row mb-4">
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>服务器主配置文件路径</Form.Label>
              <Form.Control 
                type="text" 
                value={localConfig.serverConfig} 
                onChange={(e) => handleConfigChange('serverConfig', e.target.value)} 
                className="glass-input"
                style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
              />
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                服务器主配置文件的完整路径和文件名 (如serverDZ.cfg)
              </Form.Text>
            </Form.Group>
          </div>
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>服务器配置文件夹路径</Form.Label>
              <Form.Control 
                type="text" 
                value={localConfig.serverProfile} 
                onChange={(e) => handleConfigChange('serverProfile', e.target.value)} 
                className="glass-input"
                style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
              />
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                服务器配置文件夹的完整路径
              </Form.Text>
            </Form.Group>
          </div>
        </div>

        <div className="row mb-4">
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>日志目录</Form.Label>
              <Form.Control 
                type="text" 
                value={localConfig.logDir} 
                onChange={(e) => handleConfigChange('logDir', e.target.value)} 
                className="glass-input"
                style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
              />
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                服务器日志文件的存储目录
              </Form.Text>
            </Form.Group>
          </div>
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>RPT日志文件名</Form.Label>
              <Form.Control 
                type="text" 
                value={localConfig.rptLog} 
                onChange={(e) => handleConfigChange('rptLog', e.target.value)} 
                className="glass-input"
                style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
              />
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                RPT日志文件的名称
              </Form.Text>
            </Form.Group>
          </div>
        </div>

        <div className="row mb-4">
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>实例ID</Form.Label>
              <Form.Control 
                type="number" 
                min="1" 
                max={10} 
                value={localConfig.instanceId} 
                onChange={(e) => handleConfigChange('instanceId', parseInt(e.target.value) || 1)} 
                className="glass-input"
                style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
              />
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                服务器实例ID，用于多实例环境
              </Form.Text>
            </Form.Group>
          </div>
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>备份路径</Form.Label>
              <Form.Control 
                type="text" 
                value={localConfig.backupPath} 
                onChange={(e) => handleConfigChange('backupPath', e.target.value)} 
                className="glass-input"
                style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
              />
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                服务器备份文件的存储路径
              </Form.Text>
            </Form.Group>
          </div>
        </div>
        <div className="row mb-4">
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>备份文件数量</Form.Label>
              <Form.Control 
                type="number" 
                min="1" 
                max={20} 
                value={localConfig.backupCount} 
                onChange={(e) => handleConfigChange('backupCount', parseInt(e.target.value) || 5)} 
                className="glass-input"
                style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
              />
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                保留的备份文件数量
              </Form.Text>
            </Form.Group>
          </div>
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>分片ID</Form.Label>
              <Form.Control 
                type="number" 
                min="1" 
                max={10} 
                value={localConfig.shardId || 1} 
                onChange={(e) => handleConfigChange('shardId', parseInt(e.target.value) || 1)} 
                className="glass-input"
                style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
              />
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                服务器分片ID，用于多分片环境（默认：1）
              </Form.Text>
            </Form.Group>
          </div>
        </div>

        {/* 日志设置 */}
        <h4 style={{color: '#ff6b6b', marginBottom: '15px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '5px'}}>日志设置</h4>
        <div className="row mb-4">
          <div className="col-md-4">
            <Form.Group className="mb-3">
              <Form.Check 
                type="switch" 
                id="enableLog" 
                label="启用日志" 
                checked={localConfig.enableLog === 1} 
                onChange={() => handleConfigChange('enableLog', localConfig.enableLog === 1 ? 0 : 1)} 
                className="form-switch-glow"
              />
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                启用服务器日志记录
              </Form.Text>
            </Form.Group>
          </div>
          <div className="col-md-4">
            <Form.Group className="mb-3">
              <Form.Check 
                type="switch" 
                id="enableLogFile" 
                label="启用日志文件" 
                checked={localConfig.enableLogFile === 1} 
                onChange={() => handleConfigChange('enableLogFile', localConfig.enableLogFile === 1 ? 0 : 1)} 
                className="form-switch-glow"
              />
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                将日志保存到文件
              </Form.Text>
            </Form.Group>
          </div>
          <div className="col-md-4">
            <Form.Group className="mb-3">
              <Form.Check 
                type="switch" 
                id="enableCrashDump" 
                label="启用崩溃转储" 
                checked={localConfig.enableCrashDump === 1} 
                onChange={() => handleConfigChange('enableCrashDump', localConfig.enableCrashDump === 1 ? 0 : 1)} 
                className="form-switch-glow"
              />
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                生成崩溃时的内存转储
              </Form.Text>
            </Form.Group>
          </div>
        </div>
      </Card.Body>
    </Card>
  );
};

export default PerformanceAndFileConfig;